from rest_framework import serializers
import requests, datetime

from merchants.models import *
from orders.models import *
from equity_mall.utils.sync_img_to_local import make_qrcode5
from cashbonus.models import CashActivityWhiteTable


class MerchantBankQRCodeQuestModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    file_type_str = serializers.CharField(source='get_file_type_display', read_only=True)
    file_status_str = serializers.CharField(source='get_file_status_display', read_only=True)
    create_user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBankQRCodeQuest
        fields = ['id', 'create_time', 'file', 'logs_file', 'file_type', 'file_type_str', 'file_status', 'file_status_str',
                  'total_line', 'success_line', 'error_line', 'remark', 'create_user']

    def get_create_user(self, obj):
        try:
            return obj.create_user.nickname
        except:
            return ''


class MerchantBankQRCodeListModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    is_download_str = serializers.CharField(source='get_is_download_display', read_only=True)

    class Meta:
        model = MerchantBankQRCode
        fields = ['id', 'merchant', 'code_id', 'link', 'is_download', 'is_download_str', 'visit', 'total_number', 'total_first_number']

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['prov_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data


class MerchantBankQRCodeRetrieveModelSerializer(serializers.ModelSerializer):

    merchant = serializers.SerializerMethodField(read_only=True)
    qrcode = serializers.SerializerMethodField(read_only=True)
    bind_number = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.SerializerMethodField(read_only=True)
    is_download_str = serializers.CharField(source='get_is_download_display', read_only=True)

    class Meta:
        model = MerchantBankQRCode
        fields = ['id', 'merchant', 'code_id', 'qrcode', 'link', 'bind_number', 'parent_code_id', 'is_download', 'is_download_str', 'visit', 'create_time',
                  'total_number', 'total_first_number']

    def get_create_time(self, obj):
        try:
            return obj.quest.create_time.strftime("%Y-%m-%d %H:%M:%S")
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['prov_name'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['id'] = merchant.id
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data

    def get_qrcode(self, obj):
        try:
            if not obj.qrcode:
                link = obj.link
                url = 'https://partner.douyinpay.com/api/merchant/getBankSubQrCodeValue'
                body = {
                    "code_id": obj.code_id,
                    "sign": link.replace(f'https://partner.douyinpay.com/external/bankcode?code_id={obj.code_id}&sign=', '')
                }
                response = requests.post(url=url, json=body)
                result = response.json()
                code_url = result['code_url']
                parent_code_id = result['parent_code_id']
                qrcode = make_qrcode5(obj.code_id, code_url, None)
                obj.qrcode = qrcode
                obj.parent_code_id = parent_code_id
                obj.save()
                return f'https://circle.sutpay.cn/{qrcode}'
            else:
                return obj.qrcode.url
        except:
            return ''

    def get_bind_number(self, obj):
        data = {}
        data['total_number'] = 0
        data['total_first_number'] = 0
        data['last_month_number'] = 0
        data['last_month_first_number'] = 0
        data['this_month_number'] = 0
        data['this_month_first_number'] = 0
        data['yesterday_number'] = 0
        data['yesterday_first_number'] = 0
        try:
            today = datetime.datetime.now()
            yesterday = today + datetime.timedelta(-1)
            yesterday_begin = yesterday.strftime("%Y-%m-%d 00:00:00")
            yesterday_end = yesterday.strftime("%Y-%m-%d 23:59:59")
            last_month_begin = (today.replace(day=1) + datetime.timedelta(-1)).replace(day=1).strftime("%Y-%m-%d 00:00:00")
            last_month_end = (today.replace(day=1) + datetime.timedelta(-1)).strftime("%Y-%m-%d 23:59:59")
            this_month_begin = today.replace(day=1).strftime("%Y-%m-%d 00:00:00")
            this_month_end = today.strftime("%Y-%m-%d 23:59:59")
            total_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id).count()
            total_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1).count()
            last_month_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, bind_time__gte=last_month_begin, bind_time__lte=last_month_end).count()
            last_month_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1, bind_time__gte=last_month_begin, bind_time__lte=last_month_end).count()
            this_month_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, bind_time__gte=this_month_begin, bind_time__lte=this_month_end).count()
            this_month_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1, bind_time__gte=this_month_begin, bind_time__lte=this_month_end).count()
            yesterday_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, bind_time__gte=yesterday_begin, bind_time__lte=yesterday_end).count()
            yesterday_first_number = MerchantBankQRCodeBindData.objects.filter(merchant_id=obj.merchant_id, is_first=1, bind_time__gte=yesterday_begin, bind_time__lte=yesterday_end).count()
            data['total_number'] = total_number
            data['total_first_number'] = total_first_number
            data['last_month_number'] = last_month_number
            data['last_month_first_number'] = last_month_first_number
            data['this_month_number'] = this_month_number
            data['this_month_first_number'] = this_month_first_number
            data['yesterday_number'] = yesterday_number
            data['yesterday_first_number'] = yesterday_first_number
        except:
            pass
        return data


class MerchantBankQRCodeBindDataListModelSerializer(serializers.ModelSerializer):

    is_first_str = serializers.CharField(source='get_is_first_display', read_only=True)
    card_type_str = serializers.CharField(source='get_card_type_display', read_only=True)
    bind_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBankQRCodeBindData
        fields = ['id', 'code_id', 'card_number', 'is_first', 'is_first_str', 'card_type', 'card_type_str', 'bind_time', 'merchant']

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data


class MErchantBankQPCodeStatisticsListModelSerializer(serializers.ModelSerializer):

    bind_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    merchant = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MErchantBankQPCodeStatistics
        fields = ['id', 'code_id', 'bind_time', 'merchant', 'total_number', 'total_first_number']

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['business_no'] = ''
        data['city_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['account_nine'] = ''
        try:
            merchant = obj.merchant
            level = obj.level
            data['merchant_name'] = merchant.name
            data['business_no'] = merchant.wyfMerchantID
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['account_nine'] = level.account_nine
        except:
            pass
        return data


class CashActivityWhiteTableModelSerializer(serializers.ModelSerializer):

    add_user = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    add_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = CashActivityWhiteTable
        fields = ('id', 'mobile', 'add_user', 'add_time', 'business_no', 'contact_name', 'id_card_number', 'is_admin', 'merchant')

    def get_add_user(self, obj):
        try:
            return obj.add_user.nickname
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['level_name'] = ''
        data['managermobile'] = ''
        data['managerName'] = ''
        try:
            merchant = Merchant.objects.filter(wyfMerchantID=obj.business_no).first()
            if merchant:
                data['managermobile'] = merchant.managermobile
                data['managerName'] = merchant.managerName
                data['merchant_name'] = merchant.name
                data['level_name'] = merchant.level.name
        except:
            pass
        return data